/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 新建报修工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    Modal,Linking,Clipboard
} from 'react-native';
import FontAwesome from "react-native-vector-icons/FontAwesome"
import {connect} from 'react-redux';
import {styles} from "./DepartmentalRepairOrderDetailScreen.Style";
import {FetchStatus} from "../../../../../configuration/RequestConfiguration";
import {doDisplayWarnMessage,doDisplaySuccessMessage} from "../../../../../component/Message/Action"
import {ReturnStatus} from "../../../../../configuration/ReturnStatus";
import {getDetailDs,toEditOrder} from "./Actions";
import LoadingView from "../../../../../component/LoadingView/LoadingView"
import {COLOR_LINK, FONT_COLOR_SUB_TITLE} from "../../../../../constant/PHColors";
import ChooseDealPeopleView from "../../../../../component/OrderDetailComponent/DealPeopleView";
import BottomMenuView from "../../../../../component/OrderDetailComponent/BottomMenuView";
import {AppRequestPath} from "../../../../../configuration/AppConfig";
import {AudioRecorder, AudioUtils} from "react-native-audio";
import Sound from "react-native-sound";
import {getStore} from "../../../../../configuration/StoreConfiguration";
import User from "../../../../../model/User/User";
import {API_UPLOADIMG_AUDIO} from "../../../../../constant/API";
import {SaveRepairWorkOrder} from "../../CreateRepairWorkOrderScreen/Actions";

class DepartmentalRepairOrderDetailScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '工单内容'
    })

    //构造
    constructor(props) {
        super(props);
        this.state = {
            defaultDataSource:[], //数据
            menuInfo:'', //菜单权限
            phoneNum:"",
            modalVisible:false,//电话弹出modal
            dealPeopleName:[], //处理人名称
            dealPeople:[], //处理人
            dealPeopleNameDefault:[],//默认处理人名称
            dealPeopleDefault:[], //默认处理人
            imageArr:[{},{},{},{},{}],
            soundState_c:'点击播放',

            hasPermission: undefined, //授权状态
            audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac', // 文件路径
            recording: false, //是否录音
            pause: false, //录音是否暂停
            stop: false, //录音是否停止
            currentTime: 0, //录音时长
            audioBase64:'',     //base64格式的音频文件
            repair_soundState_c:'点击播放',
        };
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;
        if (nextProps.onDepartRepairOrderDetailDefault !== this.props.onDepartRepairOrderDetailDefault && nextProps.onDepartRepairOrderDetailDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onDepartRepairOrderDetailDefault.RETURN === ReturnStatus.Success) {
                let defaultInfo = nextProps.onDepartRepairOrderDetailDefault.data;
                let menuInfo = nextProps.onDepartRepairOrderDetailDefault.operation;
                console.log(menuInfo);
                let dealPeople = [];
                let dealPeopleName = [];
                if(defaultInfo[0].work_userid_list && defaultInfo[0].work_userid_list.length>0){
                    dealPeople = defaultInfo[0].work_userid_list.split(',');
                    dealPeopleName = defaultInfo[0].work_username_list.split(',');
                }
                let imageArr = [{},{},{},{},{}];
                imageArr[0] = defaultInfo[0]["pic1"]?{"path":defaultInfo[0]["pic1"]}:{};
                imageArr[1] = defaultInfo[0]["pic2"]?{"path":defaultInfo[0]["pic2"]}:{};
                imageArr[2] = defaultInfo[0]["pic3"]?{"path":defaultInfo[0]["pic3"]}:{};
                imageArr[3] = defaultInfo[0]["pic4"]?{"path":defaultInfo[0]["pic4"]}:{};
                imageArr[4] = defaultInfo[0]["pic5"]?{"path":defaultInfo[0]["pic5"]}:{};

                let url = AudioUtils.DocumentDirectoryPath + '/test.aac'
                if((defaultInfo[0]['sound1'] && defaultInfo[0]['sound1']!=='')){
                    url = AppRequestPath().replace("qms/mobile","")+"attach/"+defaultInfo[0]['sound1'];
                }

                if((defaultInfo[0]['sound'])){
                    console.log("================================")
                }else{
                    console.log("********************************")
                }
                this.setState({
                    defaultDataSource: defaultInfo,
                    menuInfo:menuInfo,
                    dealPeople:dealPeople,
                    dealPeopleName:dealPeopleName,
                    dealPeopleDefault:dealPeople,
                    dealPeopleNameDefault:dealPeopleName,
                    imageArr:imageArr,
                    audioPath:url,
                    stop: true,
                    recording: false,
                    paused: false
                });

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onDepartRepairOrderDetailDefault.MSG))
            }
        }

        if (nextProps.onChangeOrderRemark !== this.props.onChangeOrderRemark && nextProps.onChangeOrderRemark.fetchStatus === FetchStatus.Success) {
            if (nextProps.onChangeOrderRemark.RETURN === ReturnStatus.Success) {
                let str = {"qms_repair":{"sn":this.props.navigation.getParam("sn")}};
                dispatch(getDetailDs(JSON.stringify(str)))
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onChangeOrderRemark.MSG))
            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        // this.props.navigation.navigate('MainNavigator');
        let {dispatch} = this.props;
        let _this = this;
        let str = {"qms_repair":{"sn":this.props.navigation.getParam("sn")}};
        dispatch(getDetailDs(JSON.stringify(str)))

        AudioRecorder.requestAuthorization()
            .then(isAuthor => {
                console.log('是否授权: ' + isAuthor)
                if(!isAuthor) {
                    return alert('请前往设置开启录音权限')
                }
                this.setState({hasPermission: isAuthor})
                this.prepareRecordingPath(this.state.audioPath);
                // 录音进展
                AudioRecorder.onProgress = (data) => {
                    this.setState({currentTime: Math.floor(data.currentTime)});
                };
                // 完成录音
                AudioRecorder.onFinished = (data) => {
                    // data 返回需要上传到后台的录音数据
                    console.log(this.state.currentTime)
                    console.log(data);
                    this.state.audioBase64 = data['base64']?data['base64']:'';

                    if(this.state.audioBase64!==''){
                        let token = getStore().getState().onToken;
                        User.getUser(user => {
                            let data = new FormData();
                            data.append('base64', this.state.audioBase64);
                            data.append("token", token);
                            data.append("prefix", "qms_repairOrderAudio");
                            data.append("orderid", this.state.defaultDataSource[0].area_sn+"_"+this.state.defaultDataSource[0].object_sn+"_repair");
                            data.append("hotelId", user.hotelId);
                            try {
                                fetch(AppRequestPath()+ API_UPLOADIMG_AUDIO, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'multipart/form-data;charset=utf-8'
                                    },
                                    body: data
                                }).then(function(response) {
                                    return response.json();
                                }).then(data=>{
                                    let {dispatch} = _this.props;
                                    let outJson = {"qms_repair":{"sn":_this.props.navigation.getParam('sn'),"sound1":data.DATA[0].filename}};
                                    dispatch(toEditOrder(JSON.stringify(outJson)))
                                })
                            } catch (err) {
                                console.log(err)
                            }
                        })

                    }
                };
            })
    }

    /**
     * AudioRecorder.prepareRecordingAtPath(path,option)
     * 录制路径
     * path 路径
     * option 参数
     */
    prepareRecordingPath = (path) => {
        const option = {
            SampleRate: 44100.0, //采样率
            Channels: 2, //通道
            AudioQuality: 'High', //音质
            AudioEncoding: 'aac', //音频编码
            OutputFormat: 'mpeg_4', //输出格式
            MeteringEnabled: false, //是否计量
            MeasurementMode: false, //测量模式
            AudioEncodingBitRate: 32000, //音频编码比特率
            IncludeBase64: true, //是否是base64格式
            AudioSource: 0, //音频源
        }
        AudioRecorder.prepareRecordingAtPath(path,option)
    }

    // 开始录音
    _record = async () => {
        if(!this.state.hasPermission) {
            return alert('没有授权')
        }
        if(this.state.recording) {
            return alert('正在录音中...')
        }
        if(this.state.stop) {
            this.prepareRecordingPath(this.state.audioPath)
        }
        this.setState({recording: true,pause: false})

        try {
            await AudioRecorder.startRecording()
        } catch (err) {
            console.log(err)
        }
    }

    // 暂停录音
    _pause = async () => {
        if(!this.state.recording) {
            return alert('当前未录音')
        }

        try {
            await AudioRecorder.pauseRecording()
            this.setState({pause: true, recording: false})
        } catch (err) {
            console.log(err)
        }
    }

    // 恢复录音
    _resume = async () => {
        if(!this.state.pause) {
            return alert('录音未暂停')
        }

        try {
            await AudioRecorder.resumeRecording();
            this.setState({pause: false, recording: true})
        } catch (err) {
            console.log(err)
        }
    }

    // 停止录音
    _stop = async () => {
        this.setState({stop: true, recording: false, paused: false});
        try {
            await AudioRecorder.stopRecording();
        } catch (error) {
            console.error(error);
        }


    }

    // 播放录音
    _play = async () => {
        let whoosh = new Sound(this.state.audioPath, '', (err) => {
            this.setState({repair_soundState_c:"正在播放..."})
            if(err) {
                this.setState({repair_soundState_c:"播放失败"})
                return console.log(err)
            }
            whoosh.play(success => {
                if(success) {
                    this.setState({repair_soundState_c:"点击播放"})
                    console.log('success - 播放成功')
                }else {
                    this.setState({repair_soundState_c:"播放失败"})
                    console.log('fail - 播放失败')
                }
            })
        })
    }


    render(){
        let {dispatch,onDepartRepairOrderDetailDefault} = this.props;
        let { stop, recording, pause, currentTime } = this.state;
        let _this = this;
        if ( this.state.defaultDataSource.length>0) {
            return (
                <SafeAreaView style={styles.body}>

                    <ScrollView style={styles.bodyContainer}>
                        <View style={{flexDirection: 'row'}}>
                            <View>
                                <View style={styles.boxTitle} onPress={()=>{
                                }}>
                                    {/* 标题 */}
                                    <View styles={styles.titleTop}>
                                        <Text style={styles.titleTopText}>
                                            {this.state.defaultDataSource[0]['object_name']}
                                        </Text>
                                    </View>


                                    {/* 第二行 内容 */}
                                    <View style={styles.titleBottom}>
                                        <Text style={styles.titleBottomText}>
                                            {this.state.defaultDataSource[0]['create_datetime']}  ({this.state.defaultDataSource[0]['status']})
                                        </Text>
                                    </View>

                                </View>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row'}}>
                            <View>
                                <View style={styles.boxContainer} onPress={()=>{
                                }}>
                                    {/* 标题 */}
                                    <View style={styles.container}>
                                        <Text style={styles.containerName}>
                                            对象
                                        </Text>
                                        <Text style={styles.containerText}>
                                            {this.state.defaultDataSource[0]['object_fullname']}
                                        </Text>
                                    </View>

                                    <View style={styles.container}>
                                        <Text style={styles.containerName}>
                                            报修人
                                        </Text>
                                        <Text style={styles.containerText}>
                                            {this.state.defaultDataSource[0]['report_username']}
                                        </Text>
                                    </View>

                                    <View style={styles.container}>
                                        <Text style={styles.containerName}>
                                            联系电话
                                        </Text>
                                        <Text style={styles.containerText} onPress={()=>{
                                            if(this.state.defaultDataSource[0]['report_connect']!==""){
                                                this.setState({
                                                    modalVisible: true
                                                })
                                            }
                                        }}>
                                            <FontAwesome name={'phone-square'} size={20} style={{color: COLOR_LINK, marginLeft: 10}}/>
                                            {this.state.defaultDataSource[0]['report_connect']}
                                        </Text>
                                    </View>

                                    <View style={styles.container}>
                                        <Text style={styles.containerName}>
                                            组别
                                        </Text>
                                        <Text style={styles.containerText}>
                                            {this.state.defaultDataSource[0]['type']}
                                        </Text>
                                    </View>
                                </View>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row'}}>
                            <View>
                                <View style={styles.boxRemark} onPress={()=>{
                                }}>
                                    {/* 内容 */}
                                    <View style={styles.remark}>
                                        <Text style={styles.containerName}>
                                            内容
                                        </Text>
                                        <Text style={styles.containerText}>
                                            {this.state.defaultDataSource[0]['object_content']}
                                        </Text>
                                    </View>
                                </View>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row'}}>
                            <View>
                                <View style={styles.boxRemark} onPress={()=>{
                                }}>
                                    {/* 备注 */}
                                    <View style={styles.remark}>
                                        <Text style={styles.containerName}>
                                            备注
                                        </Text>
                                        <Text style={styles.containerText}>
                                            {this.state.defaultDataSource[0]['remark']}
                                        </Text>
                                    </View>
                                </View>
                            </View>
                        </View>

                        {/*退回原因*/}
                        {
                            (typeof(this.state.defaultDataSource[0]['status_remark'])!=="undefined" && this.state.defaultDataSource[0].status_remark!=='')&&(
                                <View style={{flexDirection: 'row'}}>
                                    <View>
                                        <View style={styles.boxRemark} onPress={()=>{
                                        }}>
                                            <View style={styles.remark}>
                                                <Text style={styles.containerName}>
                                                    说明
                                                </Text>
                                                <Text style={styles.containerText}>
                                                    {this.state.defaultDataSource[0]['status_remark']?this.state.defaultDataSource[0]['status_remark']:''}
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            )
                        }

                        {/*图片*/}
                        <View style={{flexDirection: 'row'}}>
                            <View>
                                <View style={styles.boxRemark} onPress={()=>{
                                }}>
                                    {/* 备注 */}
                                    <View style={styles.remark}>
                                        <Text style={styles.containerName}>
                                            图片说明
                                        </Text>
                                        <Text style={styles.containerText_image} onPress={() => {
                                            // 跳转到选择图片上传
                                            console.log(JSON.stringify(this.state.imageArr))
                                            let _t=this;
                                            this.props.navigation.navigate('RepairWorkOrderUploadImageScreen',{"imageArr":this.state.imageArr,goBack:(data)=>{
                                                    _t.props.navigation.navigate('DepartmentalRepairOrderDetailScreen');
                                                    _t.setState({
                                                        imageArr:data
                                                    });
                                                    let str = {"qms_repair":{"sn":_t.props.navigation.getParam('sn')}};
                                                    data.map((item, index) => {
                                                        if(item!=={}){
                                                            str.qms_repair["pic"+(index+1)] = (item.path)
                                                        }
                                                    });
                                                    let {dispatch} = _t.props;
                                                    dispatch(toEditOrder(JSON.stringify(str)))
                                                }})
                                        }}>
                                            编辑图片
                                        </Text>
                                    </View>
                                </View>
                            </View>
                        </View>

                        {/*语音*/}
                        {
                            (this.state.defaultDataSource[0].hasOwnProperty('sound') && this.state.defaultDataSource[0]['sound']!=='')&&(
                                <View style={{flexDirection: 'row'}}>
                                    <View>
                                        <View style={styles.boxRemark} onPress={()=>{
                                        }}>
                                            {/* 备注 */}
                                            <View style={styles.remark}>
                                                <Text style={styles.containerName}>
                                                    语音说明
                                                </Text>
                                                <Text style={styles.containerText_image} onPress={() => {
                                                    let url = AppRequestPath().replace("qms/mobile","")+"attach/"+this.state.defaultDataSource[0]['sound']
                                                    console.log(url)
                                                    let whoosh = new Sound(url, '', (err) => {
                                                        this.setState({soundState_c:"正在播放..."})
                                                        if(err) {
                                                            this.setState({soundState_c:"播放失败"})
                                                            return console.log(err)
                                                        }
                                                        whoosh.play(success => {
                                                            if(success) {
                                                                this.setState({soundState_c:"点击播放"})
                                                                console.log('success - 播放成功')
                                                            }else {
                                                                this.setState({soundState_c:"播放失败"})
                                                                console.log('fail - 播放失败')
                                                            }
                                                        })
                                                    })
                                                }}>
                                                    {this.state.soundState_c}
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            )
                        }

                        {/*语音*/}
                        {
                                <View style={{flexDirection: 'row'}}>
                                    <View>
                                        <View style={styles.boxRemark} onPress={()=>{
                                        }}>
                                            <View style={styles.remark}>
                                                <Text style={styles.containerName}>
                                                    维修说明
                                                </Text>
                                                {
                                                    (stop && (this.state.defaultDataSource[0]['sound1'] && this.state.defaultDataSource[0]['sound1']!=='')) ? (
                                                        <View  style={[styles.containerText_image,{flexDirection:'row',}]}>
                                                            <TouchableOpacity style={{flex:0.5,}} activeOpacity={0.8} onPress={this._play}>
                                                                    <Text style={{fontSize: 20,color: '#1f60ff'}}>
                                                                        {this.state.repair_soundState_c}
                                                                    </Text>
                                                            </TouchableOpacity>

                                                            {
                                                                (this.state.defaultDataSource[0]['status']==="处理中")&&
                                                                (
                                                                    <TouchableOpacity style={{flex:0.5,}} activeOpacity={0.8} onPress={() => {
                                                                        this.state.audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac'
                                                                        this.prepareRecordingPath(this.state.audioPath);
                                                                        this.setState({stop: false, recording: false, paused: false,currentTime:0});

                                                                        let {dispatch} = _this.props;
                                                                        let outJson = {"qms_repair":{"sn":_this.props.navigation.getParam('sn'),"sound1":""}};
                                                                        dispatch(toEditOrder(JSON.stringify(outJson)))
                                                                    }}>
                                                                        <Text style={{ fontSize: 20,color: '#1f60ff'}}>
                                                                            删除
                                                                        </Text>
                                                                    </TouchableOpacity>
                                                                )
                                                            }

                                                        </View>
                                                    ): (
                                                        <TouchableOpacity style={styles.containerText_image} activeOpacity={0.8} onPressIn={this._record} onPressOut={this._stop}>
                                                            {/*<View >*/}
                                                                <Text style={{fontSize: 20,color: '#1f60ff',}}>
                                                                    {
                                                                        recording ? '正在录音 时长'+currentTime+'S' :
                                                                            pause ? '已暂停' : '按住说话'
                                                                    }
                                                                </Text>
                                                            {/*</View>*/}
                                                        </TouchableOpacity>
                                                    )
                                                }
                                            </View>
                                        </View>
                                    </View>
                                </View>
                        }

                        {/*处理人*/}
                        {
                            (this.state.menuInfo.split(',').indexOf("派工")>-1)&&
                            (
                                <ChooseDealPeopleView dealPeople={this.state.dealPeople} dealPeopleName={this.state.dealPeopleName} dealPeopleDefault={this.state.dealPeopleDefault} dealPeopleNameDefault={this.state.dealPeopleNameDefault} changeDealPeople={(dealArr,dealNameArr)=>{
                                    this.setState({
                                        dealPeople: dealArr,
                                        dealPeopleName:dealNameArr
                                    });
                                }} />
                            )
                        }



                        <View style={styles.bottomContainer}>
                            <Text style={styles.bottomContainerText}>
                                工单号：{this.state.defaultDataSource[0]['recordno']}
                            </Text>
                        </View>

                    </ScrollView>

                    <BottomMenuView operation={this.state.menuInfo} dataSource={this.state} sn={this.props.navigation.getParam("sn")}
                        toInputReason={(operationName,procedure)=>{//输入原因
                            _this.props.navigation.navigate('InputReasonScreen',{"operationName":operationName,"procedure":procedure,"sn":_this.props.navigation.getParam("sn"),
                                goBack:()=>{
                                    _this.props.navigation.navigate(this.props.navigation.getParam("beforePage"));
                                    _this.props.navigation.state.params.callBack();
                                }
                            });
                        }}
                        goBack={()=>{
                            _this.props.navigation.navigate(this.props.navigation.getParam("beforePage"));
                            _this.props.navigation.state.params.callBack();
                        }}
                        toConsumables={()=>{//耗材
                            _this.props.navigation.navigate('ConsumablesScreen',{"sn":_this.props.navigation.getParam("sn"),"beforePage":'DepartmentalRepairOrderDetailScreen',
                                goBack:()=>{
                                    let {dispatch} = _this.props;
                                    let str = {"qms_repair":{"sn":_this.props.navigation.getParam("sn")}};
                                    dispatch(getDetailDs(JSON.stringify(str)))
                                }
                            });
                        }}
                        toEditRemark={()=>{//修改备注OrderEditScreen
                            _this.props.navigation.navigate('OrderEditScreen',{"sn":_this.props.navigation.getParam("sn"),"beforePage":'DepartmentalRepairOrderDetailScreen',"remark":this.state.defaultDataSource[0]['remark'],
                                goBack:(str)=>{
                                    let {dispatch} = _this.props;
                                    dispatch(toEditOrder(JSON.stringify(str)))
                                }
                            });
                        }}
                    />

                    {/*电话*/}
                    <Modal
                        visible={this.state.modalVisible}
                        //显示是的动画默认none
                        //从下面向上滑动slide
                        //慢慢显示fade
                        animationType = {'none'}
                        //是否透明默认是不透明 false
                        transparent = {true}
                        //关闭时调用
                        onRequestClose={()=> this.onRequestClose()}
                    >
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            this.onRequestClose();
                        }}>
                            <View style={styles.modalContainer}>
                                <View style={styles.modalBox} >
                                    <View style={styles.modalTitle}>
                                        <Text style={styles.modalTitleTextNum}>
                                            {this.state.defaultDataSource[0]['report_connect']}
                                        </Text>
                                    </View>
                                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={()=>{
                                        this.onRequestClose();
                                        return Linking.openURL('tel:'+this.state.defaultDataSource[0]['report_connect']);
                                    }}>
                                        <View style={styles.modalCenter} >
                                            <Text style={styles.modalTitleText} >
                                                呼叫
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={()=>{
                                        this.onRequestClose();
                                        Clipboard.setString(this.state.defaultDataSource[0]['report_connect']);
                                    }}>
                                        <View style={styles.modalBottom}>
                                            <Text style={styles.modalTitleText}>
                                                复制
                                            </Text>
                                        </View>
                                    </TouchableOpacity>

                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>

                </SafeAreaView>
            )
        }else{
                return <LoadingView/>
        }

    }

    onRequestClose(){
        this.setState({
            modalVisible: false,
        })
    }
}



const props = state => {
    return {
        onDepartRepairOrderDetailDefault: state.onDepartRepairOrderDetailDefault,
        onChangeOrderRemark: state.onChangeOrderRemark,
    }
}

export default DepartmentalRepairOrderDetailScreen = connect(props)(DepartmentalRepairOrderDetailScreen);
